package rsschart.services;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.Writer;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;

import rsschart.charter.BarChart;
import rsschart.charter.Charter;
import rsschart.charter.CharterFactory;
import rsschart.charter.GroupBarChart;
import rsschart.charter.LineChart;
import rsschart.charter.PieChart;
import rsschart.charter.StackBarChart;
import rsschart.feed.Category;
import rsschart.feed.DataSet;
import rsschart.feed.DataSets;
import rsschart.feed.RssChart;
import rsschart.services.xml.CategoryBean;
import rsschart.services.xml.ChartBean;
import rsschart.services.xml.ConfigBean;
import rsschart.services.xml.DataSetBean;
import rsschart.services.xml.DataSetsBean;
import rsschart.services.xml.XmlProcessor;

public class PostProcessor extends HttpServlet {

		
	public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
		String requestType;
		String data;
		String content;
		Writer writer;
		
		data = request.getParameter("data");
		if (getServletConfig()==null) {
			throw new ServletException("Method wasn't called in context of web application. No servletConfig.");
		}
		requestType = getServletConfig().getInitParameter("requestType");
		
		//-- debugging
		requestType = "xml";
		
		if (requestType==null) {
			throw new ServletException("requestType not found");
		}
		
		Processor processor=null;
		try {
			processor = getProcessor(requestType);
			content = processor.convertToSvg(data);
		}
		catch(Exception e) {
			throw new ServletException(e);
		}

		writer = response.getWriter();
		writer.write(content);
	
	}

	

	
	private static Processor getProcessor(String requestType) throws Exception {
		Processor p;
		
		if (requestType.equalsIgnoreCase("xml")) {
			p = new XmlProcessor();
		}
		else {
			//-- to do: make rsschart exception class hierarchy
			throw new Exception("Undefined request type: " + requestType + ". Expected: xml|nvp|...");
		}
		return p;
		
	}

}


